<template>
    <div class="editor">
        <Toolbar style="border-bottom: 1px solid #ccc" :editor="editor" :defaultConfig="toolbarConfig" />
        <Editor style="height:400px;" @onChange="onEditChange" v-model="editorHtml" :defaultConfig="editorConfig"
            @onCreated="onCreated" />
    </div>
</template>

<script>
import { Editor, Toolbar } from '@wangeditor/editor-for-vue';
import { imageUpload } from "@/api/upload";
export default {
    name: 'RichEditor',
    props: ["resetHtml"],
    components: {
        Editor,
        Toolbar,
    },
    data() {
        let baseUrl = this.$serverPath;
        return {
            editor: null,
            editorHtml: this.resetHtml,
            toolbarConfig: {
                excludeKeys: ['fullScreen'],
                // toolbarKeys: [ ],
                // insertKeys: {}
            },
            editorConfig: {
                placeholder: '请输入内容公告...',
                autoFocus: false,
                // 其他配置...
                MENU_CONF: {
                    uploadImage: {
                        // 禁用默认的上传按钮和逻辑
                        server: null,
                        // 自定义上传逻辑
                        async customUpload(file, insertFn) {
                            try {
                                const formData = new FormData();
                                formData.append('file', file);
                                imageUpload(formData).then(response => {
                                    const imageUrl = response.data.url;
                                    insertFn(imageUrl, file.name, '');
                                })

                            } catch (error) {
                                console.error('上传失败:', error);
                                alert('上传失败，请稍后再试。');
                            }
                        }
                    },

                }
            },
        }
    },
    watch: {
        // 监听父组件传递的 inputValue，如果变化则更新 localInputValue
        resetHtml(newVal) {
            this.editorHtml = newVal;
        }
    },
    mounted() {
    },
    methods: {
        onCreated(editor) {
            // 一定要用Object.seal()，否则会报错
            this.editor = Object.seal(editor);
        },
        onEditChange(editorInstance) {
            const cleanedContent = editorInstance.getHtml()
            // .trim().replace(/^<p>[\s\S]*?<br\/?><\/p>$/, '');
            this.editorHtml = cleanedContent;
            this.$emit('onChange', cleanedContent);
        }
    }

}
</script>


<style lang="scss" scoped>
@import '@wangeditor/editor/dist/css/style.css';

.editor {
    border: 1px solid #ccc;
}
</style>